import { defineComponent, h, onMounted, onUnmounted, reactive, Ref, ref } from 'vue';
import loginStyles from '@/pages/Login/Login.module.scss';
import logoSvg from '@/assets/images/wind-logo.svg';
import { AccountType } from '@/global';
import { ElForm, ElFormItem, ElInput, ElIcon, ElButton, FormRules } from 'element-plus';
import { Unlock, User, View } from '@element-plus/icons-vue';
import useUserStore from '@/config/pania_store/module/user_store';
import { router } from '@/config/router_config';
import { RouteNameEnum } from '@/config/router_config/router_components';
import { getNamedBean, namedBean } from '@/util/reactive_obj_util';
enum LoginNamedBeanEnum {
  formRefBean
};
/**
 * 登录用户类
 */
export interface LoginUser {
  accountName: string;
  accountPassword: string;
  accountType: AccountType;
}

/**
 * 登录功能
 * @param loginUser 登录的用户
 * @param loading 加载loading对象
 */
export async function login (loginUser: LoginUser, loading: Ref<boolean>): Promise<void> {
  const formRef = getNamedBean(LoginNamedBeanEnum.formRefBean) as ReturnType<typeof ref<InstanceType<typeof ElForm>>>;
  formRef.value && formRef.value.validate().then(async result => {
    if (result) {
      const userStore = useUserStore();
      loading.value = true;
      await userStore.login(loginUser).finally(() => { loading.value = false; });
    }
  }).catch((err) => { console.log(err); });
}

/**
 * 登出功能
 */
export async function logout (): Promise<void> {
  const userStore = useUserStore();
  await userStore.logout();
  await router.push({ name: RouteNameEnum.login });
}

/**
 * 绑定点击enter键登录功能
 * @param loginUser 登录的用户
 * @param loading 加载loading对象
 */
function bindEnterKeyLogin (loginUser: LoginUser, loading: Ref<boolean>) {
  const checkEnterKey = (event: KeyboardEvent) => {
    const code = event.key;
    if (code === 'Enter') {
      login(loginUser, loading).then(() => {});
    }
  };
  onMounted(() => {
    document.addEventListener('keyup', checkEnterKey);
  });
  onUnmounted(() => {
    document.removeEventListener('keyup', checkEnterKey);
  });
}

/**
 * 登录页面组件
 */
export default defineComponent({
  name: 'LoginPage',
  setup () {
    const loginUser = reactive<LoginUser>({ accountName: '', accountPassword: '', accountType: AccountType.UserName });// 登录绑定的用户
    const isShowPassword = ref<boolean>(true); // 是否显示密码
    const submitLoading = ref<boolean>(false); // 提交加载对象
    const changeIsShowPassword = (e: Event) => { isShowPassword.value = !isShowPassword.value; };
    const loginFormRef = namedBean(ref<InstanceType<typeof ElForm> | null>(null), LoginNamedBeanEnum.formRefBean); // 表单对象
    const loginFormRules = reactive<FormRules>({
      accountName: [{ type: 'string', required: true, message: '用户名是必填项!', trigger: ['blur'] }],
      accountPassword: [{ type: 'string', required: true, message: '密码是必填项!', trigger: ['blur'] }]
    });// 登录功能校验规则
    bindEnterKeyLogin(loginUser, submitLoading); // 绑定enter键

    return () => <div class={loginStyles.wind_login_form}>
      {/* 顶部的logo区域 */}
      <div class={loginStyles.wind_logo}>
        <img src={logoSvg} alt='logo'/>
      </div>
      {/* 中间的登录区域 */}
      <div class={loginStyles.wind_login_content}>
        <div class={loginStyles.wind_login_main}>
          <div class={loginStyles.wind_login_system_title}>风旅管理后台</div>
          <ElForm model={loginUser} ref={loginFormRef} rules={loginFormRules}>
            {/* 用户名输入区域 */}
            <ElFormItem class={'form_upper_1'} prop={'accountName'}>
              <ElInput v-model={loginUser.accountName} placeholder={'请输入用户名'}>
                {{ prefix: () => <ElIcon class={'el-input__icon'}><User/></ElIcon> }}
              </ElInput>
            </ElFormItem>
            {/* 密码输入区域 */}
            <ElFormItem class={'form_upper_2'} prop={'accountPassword'}>
              {/* @ts-ignore */}
              <ElInput v-model={loginUser.accountPassword} placeholder={'请输入密码'} type={isShowPassword.value ? 'text' : 'password'} maxlength={16}>
                {{
                  prefix: () => <ElIcon class={'el-input__icon'}><Unlock/></ElIcon>,
                  suffix: () => <div onClick={changeIsShowPassword}><ElIcon class={'el-input__icon cursor-pointer'} ><View/></ElIcon></div>
                }}
              </ElInput>
            </ElFormItem>
            {/*  底部的登录区域 */}
            <ElFormItem class={'form_upper_3'}>
              <ElButton onClick={() => login(loginUser, submitLoading)} loading={submitLoading.value} class={loginStyles.wind_login_button_submit} round={true} type={'primary'}>登录</ElButton>
            </ElFormItem>
          </ElForm>
        </div>
      </div>
    </div>;
  }
});
